package com.rcw.swiperefreshrecyclerview;

import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Date;

/**
 * Created by ruancw on 2018/3/29.
 */

public class RefreshHeadView extends LinearLayout {

    //头部下拉刷新的状态标识
    public static final int STATE_NORMAL = 100;//正常状态
    public static final int STATE_RELEASE_TO_REFRESH = 101;//释放刷新
    public static final int STATE_REFRESHING = 102;//正在刷新
    public static final int STATE_DONE = 103;//刷新完成
    public static final int STATE_FAIL = 104;//刷新失败

    private int refreshState = 0;
    //触发下拉刷新的高度
    private int limitMinHeight;
    private View refreshHeadView;
    //触发刷新时的提示信息及最近刷新时间
    private TextView tvMessage,tvRefreshTime;
    //触发刷新时的图标
    private ImageView ivArrow,ivRefreshStyle;

    //下拉刷新的监听接口
    private SwipeRefreshListener swipeRefreshListener;
    //最近一次的刷新时间
    private Date lastRefreshDate;
    //是否显示最近的刷新时间
    private boolean showLastRefreshTime;
    //属性动画的数值发生器
    private ValueAnimator animator;

    /***********************自定义头部下拉刷新view的构造函数************************/
    public RefreshHeadView(Context context) {
        this(context, null);
    }

    public RefreshHeadView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RefreshHeadView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
        
    }

    /**
     * 初始化布局文件的控件
     */
    private void init() {
        //获取触发下拉刷新事件的最小高度
        limitMinHeight = getScreenHeight() / 8;

        refreshHeadView = LayoutInflater.from(getContext()).inflate(
                R.layout.head_view, null);
        tvMessage = (TextView) refreshHeadView.findViewById(R.id.tv_message);
        tvRefreshTime = (TextView) refreshHeadView.findViewById(R.id.tv_refresh_time);
        ivArrow = (ImageView) refreshHeadView.findViewById(R.id.iv_arrow);
        ivRefreshStyle = (ImageView) refreshHeadView.findViewById(R.id.iv_refresh);
        //不显示刷新布局,设置高度为0
        addView(refreshHeadView, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
    }

    /**
     * 设置触发下拉刷新的高度
     * @param height
     */
    public void setLimitMinHeight(int height) {
        limitMinHeight = height;
    }

    /**
     * 设置下拉刷新的布局背景
     * @param resId
     */
    public void setRefreshBackground(int resId) {
        refreshHeadView.setBackgroundResource(resId);
    }

    /**
     * 设置刷新提示的图片资源
     * @param resId
     */
    public void setRefreshArrowResource(int resId) {
        ivArrow.setImageResource(resId);
    }

    /**
     * 设置刷新时的图片资源
     * @param resId
     */
    public void setRefreshingResource(int resId) {
        ivRefreshStyle.setImageResource(resId);
    }

    /**
     * 显示最近一次的刷新时间
     * @param display
     */
    public void displayLastRefreshTime(boolean display) {
        showLastRefreshTime = display;
    }

    /**
     * 下拉刷新的移动事件
     * @param move
     */
    public void onMove(int move) {
        int newVisibleHeight = getHeadVisibleHeight() + move;
        if (newVisibleHeight >= limitMinHeight && refreshState != STATE_RELEASE_TO_REFRESH) {
            if (ivArrow.getVisibility() != VISIBLE) ivArrow.setVisibility(VISIBLE);
            refreshState = STATE_RELEASE_TO_REFRESH;
            tvMessage.setText(R.string.release_refresh);
            rotationAnimator(180f);
        }
        if (newVisibleHeight < limitMinHeight && refreshState != STATE_NORMAL) {
            if (ivArrow.getVisibility() != VISIBLE) ivArrow.setVisibility(VISIBLE);
            refreshState = STATE_NORMAL;
            tvMessage.setText(R.string.pull_refresh);
            if (lastRefreshDate == null) {
                tvRefreshTime.setVisibility(GONE);
            } else {
                if (showLastRefreshTime) {
                    tvRefreshTime.setVisibility(VISIBLE);
                    tvRefreshTime.setText(friendlyTime(lastRefreshDate));
                }
            }
            rotationAnimator(0);
        }
        //设置可见头部高度
        setHeadVisibleHeight(getHeadVisibleHeight() + move);
    }

    /**
     * 设置recyclerView触摸事件结束后检查是否需要刷新
     */
    public void checkRefresh() {
        if (getHeadVisibleHeight() <= 0) return;
        if (refreshState == STATE_NORMAL) {
            smoothScrollTo(0);
            refreshState = STATE_DONE;
        } else if (refreshState == STATE_RELEASE_TO_REFRESH) {
            setState(STATE_REFRESHING);
        }
    }

    /**
     * 设置正在刷新时的资源
     */
    public void setRefreshing() {
        refreshState = STATE_REFRESHING;
        ivArrow.setVisibility(GONE);
        tvRefreshTime.setVisibility(GONE);
        ivRefreshStyle.setVisibility(VISIBLE);
        startRefreshingAnimation();
        tvMessage.setText(R.string.refresh);
        smoothScrollTo(getScreenHeight() / 9);
        if (swipeRefreshListener != null) {
            swipeRefreshListener.onRefresh();
        }
    }

    /**
     * 设置刷新时的动画
     */
    public void startRefreshingAnimation() {
        animator = ValueAnimator.ofFloat(ivRefreshStyle.getRotation(), ivRefreshStyle.getRotation() + 359);
        animator.setDuration(1000).start();
        animator.setInterpolator(new LinearInterpolator());
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                ivRefreshStyle.setRotation((Float) animation.getAnimatedValue());
            }
        });
        animator.start();

    }

    /**
     * 设置下拉刷新的状态
     * @param state int 状态
     */
    public void setState(int state) {
        if (refreshState == state) return;
        switch (state) {
            case STATE_REFRESHING://正在刷新
                refreshState = state;
                ivArrow.setVisibility(GONE);
                tvRefreshTime.setVisibility(GONE);
                ivRefreshStyle.setVisibility(VISIBLE);
                startRefreshingAnimation();
                tvMessage.setText(R.string.refresh);
                smoothScrollTo(getScreenHeight() / 9);

                if (swipeRefreshListener != null) {
                    swipeRefreshListener.onRefresh();
                }
                break;
            case STATE_DONE://刷新完成
                if (refreshState == STATE_REFRESHING) {
                    refreshState = state;
                    animator.end();
                    ivRefreshStyle.setVisibility(GONE);
                    tvMessage.setText(R.string.refresh_success);
                    lastRefreshDate = new Date();
                    smoothScrollTo(0);
                }
                break;
            case STATE_FAIL://刷新失败
                if (refreshState == STATE_REFRESHING) {
                    refreshState = state;
                    ivRefreshStyle.setVisibility(GONE);
                    ivArrow.setVisibility(VISIBLE);
                    tvMessage.setText(R.string.refresh_fail);
                    animator.end();
                    smoothScrollTo(0);
                    Toast.makeText(getContext(), R.string.refresh_fail,Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    /**
     * 获取headView当前的状态值
     * @return
     */
    public int getRefreshState() {
        return refreshState;
    }

    /**
     * 设置刷新完成后的操作
     * @param loadMoreView 加载更多的view
     */
    public void setRefreshComplete(LoadMoreView loadMoreView) {
        //解决添加“没有更多了”的布局后再次刷新时不隐藏的问题
        loadMoreView.setVisibility(GONE);
        setState(STATE_DONE);
        //解决添加“没有更多了”的布局后再次刷新时隐藏后不显示加载更多布局的问题
        loadMoreView.rlNoMoreData.setVisibility(GONE);//隐藏没有更多了布局
        loadMoreView.rlLoadMore.setVisibility(VISIBLE);//显示加载更多布局
    }

    /**
     * 设置刷新失败的状态
     */
    public void setRefreshFail() {
        setState(STATE_FAIL);
    }

    /**
     * 获取下拉刷新头部view的可见高度
     * @return
     */
    public int getHeadVisibleHeight() {
        LayoutParams layoutParams = (LayoutParams) refreshHeadView.getLayoutParams();
        return layoutParams.height;
    }

    /**
     * 设置下拉刷新view可见部分的高度
     * @param height
     */
    public void setHeadVisibleHeight(int height) {
        if (height < 0) height = 0;
        LayoutParams lp = (LayoutParams) refreshHeadView.getLayoutParams();
        lp.height = height;
        refreshHeadView.setLayoutParams(lp);
    }

    /**
     * 设置下拉刷新的监听接口
     * @param swipeRefreshListener 下拉刷新和上拉加载更多接口
     */
    public void setSwipeRefreshListener(SwipeRefreshListener swipeRefreshListener) {
        this.swipeRefreshListener = swipeRefreshListener;
    }

    /**
     *下拉刷新图标旋转动画设置
     * @param rotation float 旋转的值
     */
    private void rotationAnimator(float rotation) {
        ValueAnimator animator = ValueAnimator.ofFloat(ivArrow.getRotation(), rotation);
        animator.setDuration(200).start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                ivArrow.setRotation((Float) animation.getAnimatedValue());
            }
        });
        animator.start();
    }

    /**
     * view平滑动画
     * @param destHeight 滑动的高度
     */
    private void smoothScrollTo(int destHeight) {
        ValueAnimator animator = ValueAnimator.ofInt(getHeadVisibleHeight(), destHeight);
        animator.setDuration(300).start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                setHeadVisibleHeight((int) animation.getAnimatedValue());
            }
        });
        animator.start();
    }

    /**
     * 获取屏幕高度
     * @return int
     */
    private int getScreenHeight() {
        WindowManager windowManager = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        return windowManager.getDefaultDisplay().getHeight();
    }

    /**
     * 时间友好提示
     * @param time
     * @return
     */
    public static String friendlyTime(Date time) {
        //获取time距离当前的秒数
        int ct = (int) ((System.currentTimeMillis() - time.getTime()) / 1000);

        if (ct == 0) {
            return "刚刚";
        }

        if (ct > 0 && ct < 60) {
            return ct + "秒前";
        }

        if (ct >= 60 && ct < 3600) {
            return Math.max(ct / 60, 1) + "分钟前";
        }
        if (ct >= 3600 && ct < 86400)
            return ct / 3600 + "小时前";
        if (ct >= 86400 && ct < 2592000) { //86400 * 30
            int day = ct / 86400;
            return day + "天前";
        }
        if (ct >= 2592000 && ct < 31104000) { //86400 * 30
            return ct / 2592000 + "月前";
        }
        return ct / 31104000 + "年前";
    }
}
